<template>
	<div class="container">
		<!-- 		<div class="customer-info" v-if="cancelMsg">
			<div class="section-title">
				<font style="color: red;">驳回原因：{{ cancelMsg }}</font>
			</div>
		</div> -->
		<!-- <u-notify ref="uNotify" style="padding: 10px;"></u-notify> -->
		<!-- 选择户头的框 -->
		<div class="customer-info">
			<div class="section-title">
				<image src="https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/tab_user_s.png"
					style="width: 20px; height: 20px; margin-right: 8px;">
				</image>
				客户信息
			</div>
			<!-- 包裹表单元素，添加 ref 和 rules 绑定 -->
			<div class="form-container">
				<uni-forms ref="form" :value="form" :rules="rules">
					<uni-forms-item label="公户名称" label-width="80px" name="customerCode" required label-align="right">
						<zxz-uni-data-select :disabled="billStatus === '1' || billStatus === '3'" filterable
							dataKey="showValue" dataValue="commonCode" v-model="form.customerCode" emptyTips="请输入客户名称"
							placeholder="请选择客户名称" :localdata="customerCodeOption" @inputChange="selectCustomer"
							@change="selectAccountId(0)" />
					</uni-forms-item>
					<uni-forms-item label="银行户头" label-width="80px" name="accountId" required label-align="right">
						<zxz-uni-data-select :disabled="billStatus === '1' || billStatus === '3'" filterable
							dataKey="accountName" dataValue="accountId" v-model="form.accountId" placeholder="请选择银行户头"
							:localdata="accountIdOption" />
					</uni-forms-item>
					<!-- 新增提报日期（仅当selectedGood为'72'时显示） -->
					<uni-forms-item label="提报日期" label-width="80px" name="reportDate" required label-align="right"
						v-if="isDate">
						<uni-datetime-picker :disabled="billStatus === '1' || billStatus === '3'" type="date"
							v-model="form.reportDate" placeholder="请选择提报日期" :start="startDate" :end="endDate"
							value-format="yyyy-MM-dd" />
					</uni-forms-item>
					<uni-forms-item label="经办人" label-width="80px" name="handlerCode" label-align="right">
						<zxz-uni-data-select :disabled="billStatus === '1' || billStatus === '3'" filterable
							dataKey="showValue" dataValue="commonCode" v-model="form.handlerCode" emptyTips="请输入经办人名称"
							placeholder="请选择经办人" :localdata="handlerCodeOption" @inputChange="selectHandler"
							@change="onHandlerChange" class="ellipsis-text" />
					</uni-forms-item>
				</uni-forms>
			</div>
		</div>

		<!-- 选择司机的框 -->
		<div class="driver-info">
			<div class="section-title">
				<image src="https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/icon_my_shouhuo.png"
					style="width: 20px; height: 20px; margin-right: 8px;"></image>
				司机信息
			</div>
			<div class="form-container">
				<u-button @click="addDriver" type="error" shape="circle"
					:disabled="billStatus === '1' || billStatus === '3'">
					<image src="https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/plus-sign.png"
						style="width: 20px; height: 20px; margin-right: 8px;"></image>
					<view>新增司机</view>
				</u-button>
				<div>
					<uni-collapse accordion @change="handleCollapseChange">
						<div style="display: flex;gap: 2px;justify-content: space-between;align-items: center;"
							v-for="(driver, index) in form.drivers">
							<uni-collapse-item :style="!isOpen ? 'width: calc(100% - 85px);' : 'width: 100%'"
								:title="`${driver.licensePlate} - ${driver.phoneNumber}`">
								<view class="driver-content">
									<uni-forms ref="driverForm" :value="newDriver">
										<uni-forms-item label="车牌号:" label-width="80px" name="licensePlate" required
											label-align="right">
											<uni-easyinput placeholder="请输入车牌号" v-model="driver.licensePlate"
												disabled />
										</uni-forms-item>
										<uni-forms-item label="司机名称:" label-width="80px" name="driverName"
											label-align="right">
											<uni-easyinput placeholder="请输入司机名称" v-model="driver.driverName" disabled />
										</uni-forms-item>
										<uni-forms-item label="司机电话:" label-width="80px" name="phoneNumber" required
											label-align="right">
											<uni-easyinput type="number" placeholder="请输入司机电话"
												v-model="driver.phoneNumber" disabled/>
										</uni-forms-item>
										<uni-forms-item label="装车吨位:" label-width="80px" name="carWeight" required
											label-align="right">
											<uni-easyinput type="digit" placeholder="请输入装车吨位" v-model="driver.carWeight"
												disabled />
										</uni-forms-item>
										<uni-forms-item label="身份证号:" label-width="80px" name="idCardNumber"
											label-align="right">
											<uni-easyinput type="idcard" placeholder="请输入身份证号"
												v-model="driver.idCardNumber" disabled />
										</uni-forms-item>
										<uni-forms-item label="预计日期" label-width="80px" name="toDate"
											label-align="right">
											<uni-datetime-picker disabled type="date" v-model="driver.toDate"
												placeholder="请选择预计到达时间" />
										</uni-forms-item>
										<uni-forms-item label="备注:" label-width="80px" name="remarks"
											label-align="right">
											<uni-easyinput placeholder="请输入备注" v-model="driver.remarks" disabled />
										</uni-forms-item>
									</uni-forms>
									<u-button @click="editDriver(driver, index)" type="error"
										:disabled="billStatus === '1' || billStatus === '3'" shape="circle"
										v-if="isOpen">修改司机信息</u-button>
								</view>
							</uni-collapse-item>
							<view v-if="!isOpen" style="display: flex;gap: 5px; width: 85px;"
								:class="[isOpen ? 'edit-column' : '']">
								<uni-icons type="search" size="24" color="#dd524d"
									@click="handleProcess(driver)"></uni-icons>
								<uni-icons type="trash" size="24" color="#dd524d"
									:disabled="billStatus === '1' || billStatus === '3'"
									@click="billStatus !== '1' && billStatus !== '3' ? removeDriver(index) : null"></uni-icons>
								<u-icon v-if="!isOpen" name="edit-pen" size="24" color="#dd524d"
									@click="editDriver(driver, index)"></u-icon>
							</view>

						</div>
					</uni-collapse>
				</div>
			</div>
			<!-- 新增的弹出框 -->
			<uni-popup ref="addDriverPopup" type="bottom">
				<view class="popup-content">
					<!-- 车牌号输入组件 -->
					<view style="display: flex;align-items: center;">
						<view style="width: 22%;text-align: right;">车牌号：</view>
						<AddIcensePlate :licensePlate="newDriver.licensePlate" style="width: 78%;"
							@closeKeyboard="setLicensePlate" />
					</view>

					<!-- 表单部分 -->
					<uni-forms ref="addDriverForm" :model="newDriver" :rules="driverRules">
						<uni-forms-item label="司机名称:" label-align="right" label-width="80px" name="driverName">
							<uni-easyinput placeholder="请输入司机名称" v-model="newDriver.driverName" maxlength="50" />
						</uni-forms-item>
						<uni-forms-item label="司机电话:" label-align="right" label-width="80px" name="phoneNumber"
							required>
							<uni-easyinput type="number" placeholder="请输入司机电话" v-model="newDriver.phoneNumber"
								maxlength="11"/>
						</uni-forms-item>
						<uni-forms-item label="装车吨位:" label-align="right" label-width="80px" name="carWeight" required>
							<uni-easyinput type="digit" placeholder="请输入装车吨位" v-model="newDriver.carWeight"
								maxlength="10"/>
						</uni-forms-item>
						<uni-forms-item label="身份证号:" label-align="right" label-width="80px" name="idCardNumber">
							<uni-easyinput type="idcard" placeholder="请输入身份证号" v-model="newDriver.idCardNumber"
								maxlength="18"/>
						</uni-forms-item>
						<uni-forms-item label="预计日期" label-align="right" label-width="80px" name="toDate">
							<uni-datetime-picker type="date" v-model="newDriver.toDate" placeholder="请选择预计到达时间"
								:start="getCurrentDate()" />
						</uni-forms-item>
						<uni-forms-item label="备注:" label-align="right" label-width="80px" name="remarks">
							<uni-easyinput placeholder="请输入备注" v-model="newDriver.remarks" maxlength="50" />
						</uni-forms-item>

					</uni-forms>

					<!-- 按钮组 -->
					<div class="button-group">
						<u-button type="primary" @click="addNewDriver"
							:disabled="billStatus === '1' || billStatus === '3'">确定</u-button>
						<u-button @click="closeAddDriverPopup">取消</u-button>
					</div>
				</view>
			</uni-popup>
		</div>
		<!-- 合同信息部分 -->
		<!-- <div class="contract-info">
			<div class="section-title">
				<image src="https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/icon_my_payment.png"
					style="width: 20px; height: 20px; margin-right: 8px;"></image>
				合同信息
			</div>
			<div class="form-container">
				<uni-forms-item label="是否上传" label-width="80px" name="value" required label-align="right">
					<uni-data-checkbox v-model="value"
						:disabled="billStatus === '1' || billStatus === '3' || billNumber === null || billNumber === '' || billNumber === undefined " selectedColor="#FF4250"
						:localdata="range" @change="change(value)"></uni-data-checkbox>
				</uni-forms-item>
				<u-button @click="uploadContract" :disabled="value !== 1 || (billStatus === '1' || billStatus === '3')" type="error" shape="circle">
					<image
						src="https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/icon_my_payment.png"
						style="width: 20px; height: 20px; margin-right: 8px;"></image>
					<view>上传合同</view>
				</u-button>
				<div class="contract-list" v-if="contractList.length > 0">
					<ul>
						<li v-for="(contract, index) in contractList" :key="index">
							<view>{{ contract.name }}</view>
							<div class="contract-actions">
								<uni-icons type="eye" size="24" @click="previewContract(contract)"
									style="margin-right: 15px;" color="#dd524d"></uni-icons>
								<uni-icons id="contract-trash" :disabled="billStatus === '1' || billStatus === '3'"
								 type="trash" size="24" @click="billStatus !== '1' && billStatus !== '3' ? removeContract(index) : null"
								 color="#dd524d"></uni-icons>
							</div>
						</li>
					</ul>
				</div>
			</div>
		</div> -->

		<!-- 显示所选商品及数量和预估价格 -->
		<div class="goods-info">
			<div class="goods-card">

				<div class="goods-content">
					<image class="goods-image" :src="pictureUrl" mode="aspectFill"></image>
					<div class="goods-details">
						<div class="goods-name" style="width: 240rpx;">{{ selectedGood.commodityName }}</div>
						<div class="goods-unit">{{ selectedGood.unitName }}</div>
						<div class="goods-price">单价:{{ priceToFixed() }}</div>
						<div class="goods-price">总价:{{ calculateTotalPrice() }}</div>
					</div>
					<div class="goods-quantity">
						<button :disabled="billStatus === '1' || billStatus === '3'" class="quantity-btn"
							@click="decreaseCount">-</button>
						<input :disabled="billStatus === '1' || billStatus === '3'" type="number"
							v-model="selectedGood.count" class="quantity-input" />
						<button :disabled="billStatus === '1' || billStatus === '3'" class="quantity-btn"
							@click="increaseCount">+</button>
					</div>
				</div>
			</div>
		</div>
		<!-- 返回和提交按钮 -->
		<div class="button-container">
			<view class="xieyi text-center" style="margin-bottom: 10px;">
				<checkbox-group @change="checkboxChange">
					<checkbox :checked="isAgree" value="1" style="transform:scale(0.7)" :disabled="checkboxDisabled" />
					<text class="text-grey1" style="font-size: 1px;">单价不作为最后成交价，最终成交价以当日公示价格及实际到车为准</text>
				</checkbox-group>
			</view>
			<div class="button-group">
				<u-button v-if="showResubmitButton" type="warning" @click="handleResubmit">再次提报</u-button>
				<u-button v-if="billStatus == '1'" @click="cancelReport">撤销</u-button>
				<u-button v-if="billStatus == '0' || !isEdit || billStatus == '2'" type="warning"
					@click="editOrder(false)">保存</u-button>
				<u-button v-if="billStatus == '0' || billStatus == '2'" type="warning"
					@click="editOrder(true)">提报</u-button>
				<u-button v-if="!isEdit" type="warning" @click="submitOrder(true)">提报</u-button>
				
				<u-button @click="closeDispatchPage">返回</u-button>
			</div>
		</div>
		<u-loading-page :loading="isPageLoading" loading-color="#dd524d" color="#dd524d" bgColor="#ffffffd3"
			iconSize="30px"></u-loading-page>

	</div>
</template>


<script>
	import {
		selectAccountInfo,
		selectCardNumberInfo,
		addGoodsInfo,
		editGoodsInfo,
		delPlanItem,
		cancelPlan,
		editContract,
		getParameterInfo,
		getGoodInfoNew
	} from '@/api/goods/goods.js';
	import config from '@/config.js';
	import AddIcensePlate from './AddIcensePlate.vue';
	export default {
		components: {
			AddIcensePlate
		},
		onLoad(options) {
			// this.selectCustomer();
			if(options.goodInfoDetail) this.formData=JSON.parse(options.goodInfoDetail)
			this.getParameter();
			if (options.resubmitData) {
				try {
					const resubmitData = JSON.parse(decodeURIComponent(options.resubmitData));
					// 只赋值form中已有字段，避免结构丢失
					if (resubmitData.userInfo) {
						Object.assign(this.form, resubmitData.userInfo);
					} else {
						// 确保form结构完整
						this.form = Object.assign({
							customerCode: null,
							customerName: null,
							reportDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
							accountId: null,
							submitPrice: 0,
							drivers: [],
							handlerCode: null,
							handlerName: null
						}, this.form);
					}
					this.form.drivers = resubmitData.driverInfo || [];
					this.selectedGood = resubmitData.selectedGoods && resubmitData.selectedGoods[0] ? resubmitData.selectedGoods[0] : {};
					this.isEdit = false; // 新增状态
					this.billNumber = null;
					this.billStatus = null;
					// this.isSuccess = '0';

					// 商品图片
					this.pictureUrl = this.selectedGood.pictureUrl || null;

					// 提报日期类型
					this.isDate = (this.selectedGood.goodCategoryId == '72');

					// 提报日期改为当前日期
					this.form.reportDate = this.parseTime(new Date(), '{y}-{m}-{d}');

					// 拉取客户、银行户头、经办人选项并设置选中项
					this.selectCustomer(this.form.customerName || '');
					this.selectAccountId(1); // 1表示回显
					this.selectHandler(this.form.handlerName || '');

					// 如果有传递的名称，直接使用
					if (resubmitData.customerName) {
						this.form.customerName = resubmitData.customerName;
					}
					if (resubmitData.handlerName) {
						this.form.handlerName = resubmitData.handlerName;
					}

				} catch (e) {
					console.error('解析resubmitData失败', e);
				}
				return;
			}

			if (options.goodInfoDetail) {
				try {
					this.goodInfoDetail = JSON.parse(options.goodInfoDetail);
					// this.isSuccess = this.goodInfoDetail.userInfo.completionStatus
					this.cancelMsg = this.goodInfoDetail.userInfo.cancelMsg
				} catch (error) {
					console.error('解析传递的数据时出错:', error);
				}
			}
			if (options.needDataFeedback === 'true') {
				this.billNumber = options.billNumber;
				this.isEdit = true;
				this.pictureUrl = options.pictureUrl;
				this.dataFeedback();
			} else {
				this.selectedGood = JSON.parse(options.selectedGood);

				if ('72' == this.selectedGood.goodCategoryId) {
					this.isDate = true;
				}
				this.pictureUrl = this.selectedGood.pictureUrl;
			}
		},
		data() {
			return {
				cancelMsg: null,
				// isSuccess: '0',
				isPageLoading: false,
				currentDriverIndex: null,
				// 折叠司机信息
				isOpen: false,
				value: 0,
				range: [{
					"value": 0,
					"text": "否"
				}, {
					"value": 1,
					"text": "是"
				}],
				formData:null,
				accordionVal: '1', // 折叠司机信息
				uploadImgUrl: config.baseUrl + "/data/appCommodity/ossUpload",
				form: {
					customerCode: null,
					customerName: null,
					reportDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
					accountId: null,
					submitPrice: 0,
					drivers: [],
					handlerCode: null,
					handlerName: null
				},
				newForm: {},
				fileName: null,
				filePath: null,
				parameterList: [],
				pictureUrl: null,
				billNumber: null, // 订单号
				goodInfoDetail: [], // 商品信息
				contractList: [], // 合同列表
				billStatus: null, // 订单状态
				// customerCode: null,
				// accountId: null,
				isEdit: false, // 是否编辑
				showNotify: false,
				params: {
					customerName: '',
					deptId: this.$store.state.user.deptId,
				},
				accountParams: {
					codeId: null
				},
				customerCodeOption: [], // 客户名称选项
				accountIdOption: [], // 银行户头选项
				selectedGood: {}, // 所选商品
				isDate: false,
				startDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
				endDate: this.parseTime(new Date().getTime() + (24 * 60 * 60 * 1000), '{y}-{m}-{d}'),
				// 表单规则
				rules: {
					customerCode: {
						rules: [{
							required: true,
							errorMessage: '请选择客户名称'
						}]
					},
					accountId: {
						rules: [{
							required: true,
							errorMessage: '请选择银行户头'
						}]
					},
					reportDate: {
						rules: [{
							required: true,
							errorMessage: '请选择提报时间'
						}]
					}
				},
				// 新增司机
				newDriver: {
					licensePlate: '',
					driverName: '',
					phoneNumber: '',
					remarks: '',
					carWeight: '',
					idCardNumber: '',
					toDate: '',
					isCollapsed: true
				},
				// 司机规则
				driverRules: {
					licensePlate: {
						rules: [{
							required: true,
							errorMessage: '请输入车牌号'
						}]
					},
					phoneNumber: {
						rules: [{
							required: true,
							errorMessage: '请输入司机电话'
						}]
					},
					carWeight: {
						rules: [{
							required: true,
							errorMessage: '请输入装车吨位'
						}]
					}
				},
				customerParams: {
					customerName: '',
					deptId: this.$store.state.user.deptId,
				},
				handlerParams: {
					customerName: '',
					deptId: this.$store.state.user.deptId,
				},
				handlerCodeOption: [],  // 经办人选项
				agreeChecked: [], // 复选框选中项，数组
				isAgree: false, // 是否同意协议
				checkboxDisabled: false, // 新增：checkbox是否禁用
			};
		},
		methods: {
			getParameter() {
				const data = {
					insystem: '3',
					innode: '1',
				};
				getParameterInfo(data).then(resp => {
					this.parameterList = resp.rows
				});
			},
			// 司机流程
			handleProcess(driver) {
				if (this.goodInfoDetail.userInfo.billStatus != '3') {
					this.$modal.msgError("暂无车辆流程");
					return;
				}

				let {
					originalBillNumber,
					id,
					goodsId,
					carStatus
				} = driver
				uni.navigateTo({
					url: `/pages/mindmap/trackInfo?originalBillNumber=${originalBillNumber}&id=${id}&goodsId=${goodsId}&carStatus=${carStatus}`
				});
			},
			// 折叠司机信息
			handleCollapseChange(index) {
				if (index) {
					this.isOpen = true;
				} else {
					this.isOpen = false;
				}
			},

			// 编辑司机信息
			editDriver(driver, index) {
				this.currentDriverIndex = index;
				this.showAddDriverPopup();
				// 创建一个新对象来避免直接引用
				this.newDriver = {
					...driver
				};
			},
			// 设置车牌号
			setLicensePlate(plateNumber) {
				this.newDriver.licensePlate = plateNumber.join('');
			},
			// 设置车牌号
			change(e) {
				if (e == 0) {
					if (this.billNumber === null || this.billNumber === '' || this.billNumber === undefined) {
						return;
					}
					const datainfo = {
						billNumber: this.billNumber,
						isContract: this.value,
					};
					editContract(datainfo).then(resp => {
						if (resp.code === 200) {
							this.contractList = [];
							this.fileName = null;
							this.filePath = null;
						} else {
							this.$modal.msgError("删除合同失败");
						}
					});
				}
			},
			handleResubmit() {
				// console.log(this.formData);
				// 组装 userInfo
				const userInfo = this.formData.userInfo;
				delete userInfo.billNumber;

				// 组装 driverInfo
				const driverInfo = (this.form.drivers || []).map(driver => {
					const d = { ...driver };
					delete d.billNumber;
					delete d.originalBillNumber;
					delete d.accountDate;
					return d;
				});
				// 组装 selectedGoods
				const selectedGoods = [{ ...this.selectedGood }];
				// 组装参数，直接使用当前页面显示的值
				const data = {
					userInfo,
					driverInfo,
					selectedGoods,
					isCommit: true,
					customerName: this.form.customerName || '',
					handlerName: this.form.handlerName || '',
					
				};
				
				// 跳转到新增页面，带上参数
				uni.navigateTo({
					url: '/pages/goods/dispatch?resubmitData=' + encodeURIComponent(JSON.stringify(data))
				});
			},
			// 上传文件到服务器
			async uploadFileToServer(tempFile) {
				try {

					if (this.billNumber === null || this.billNumber === '' || this.billNumber === undefined) {
						this.$modal.msgError("请先保存订单");
						return;
					}

					uni.showLoading({
						title: '上传中...',
						mask: true
					});

					// 微信小程序环境使用uni.uploadFile
					const res = await new Promise((resolve, reject) => {
						uni.uploadFile({
							url: this.uploadImgUrl,
							filePath: tempFile.path,
							name: 'file',
							formData: {},
							success: (uploadRes) => {
								try {
									resolve(JSON.parse(uploadRes.data));
								} catch (e) {
									resolve(uploadRes.data);
								}
							},
							fail: (err) => reject(err)
						});
					});
					if (res.code === 200) {
						// 表单验证通过，提交数据
						const datainfo = {
							billNumber: this.billNumber,
							fileName: this.fileName,
							contractAddress: res.url,
							isContract: this.value,
						};

						editContract(datainfo).then(resp => {
							if (resp.code === 200) {
								uni.showToast({
									title: '上传成功',
									icon: 'success'
								});
								// 上传成功，添加到合同列表
								const contract = {
									name: this.fileName,
									path: res.url, // 使用服务器返回的URL
									ossId: res.newFileName, // 保存文件ID，用于后续操作
									fileName: this.fileName,
									originalFilename: res.originalFilename,
								};
								this.contractList.push(contract);
							} else {
								this.$modal.msgError("上传失败");
							}
						});

					} else {
						this.$modal.msgError("上传失败");
					}

					uni.hideLoading();
					// ... rest of the code remains the same ...
				} catch (err) {
					uni.hideLoading();
					console.error('上传文件失败:', err);
					uni.showToast({
						title: err.message || '上传失败',
						icon: 'none'
					});
				}
			},

			// 上传合同
			uploadContract() {
				// #ifdef MP-WEIXIN
				// 微信小程序环境
				wx.chooseMessageFile({
					count: 1,
					type: 'file',
					extension: ['doc', 'docx', 'pdf'], // 只允许文档类型
					success: (res) => {
						const tempFile = res.tempFiles[0];
						this.fileName = tempFile.name;
						// 检查文件类型
						const fileExtension = tempFile.name.split('.').pop().toLowerCase();
						const allowedTypes = ['doc', 'docx', 'pdf'];
						if (!allowedTypes.includes(fileExtension)) {
							uni.showToast({
								title: '只能上传Word或PDF文件',
								icon: 'none'
							});
							return;
						}

						// 检查文件大小（限制为10MB）
						const maxSize = 10 * 1024 * 1024;
						if (tempFile.size > maxSize) {
							uni.showToast({
								title: '文件大小不能超过10MB',
								icon: 'none'
							});
							return;
						}
						if (this.contractList.length > 0) {
							uni.showToast({
								title: '只能上传一个合同信息',
								icon: 'none'
							});
							return;
						}
						// 上传到服务器
						this.uploadFileToServer(tempFile);
					},
					fail: (err) => {
						console.error('选择文件失败:', err);
						uni.showToast({
							title: '选择文件失败',
							icon: 'none'
						});
					}
				});
				// #endif

				// #ifdef H5 || APP-PLUS
				// H5或APP环境
				uni.chooseFile({
					count: 1,
					type: 'all', // 改为 'all' 允许从文件系统选择
					extension: ['doc', 'docx', 'pdf'], // 只允许文档类型
					success: (res) => {
						const tempFile = res.tempFiles[0];

						// 检查文件类型
						this.fileName = tempFile.name;
						const fileExtension = tempFile.name.split('.').pop().toLowerCase();
						const allowedTypes = ['doc', 'docx', 'pdf'];
						if (!allowedTypes.includes(fileExtension)) {
							uni.showToast({
								title: '只能上传Word或PDF文件',
								icon: 'none'
							});
							return;
						}

						// 检查文件大小（限制为10MB）
						const maxSize = 10 * 1024 * 1024;
						if (tempFile.size > maxSize) {
							uni.showToast({
								title: '文件大小不能超过10MB',
								icon: 'none'
							});
							return;
						}
						if (this.contractList.length > 0) {
							uni.showToast({
								title: '只能上传一个合同信息',
								icon: 'none'
							});
							return;
						}

						// 上传到服务器
						this.uploadFileToServer(tempFile);
					},
					fail: (err) => {
						console.error('选择文件失败:', err);
						uni.showToast({
							title: '选择文件失败',
							icon: 'none'
						});
					}
				});
				// #endif
			},
			// 获取当前日期
			getCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			resetDriver(isCollapsed) {
				return {
					licensePlate: '',
					driverName: '',
					phoneNumber: '',
					remarks: '',
					carWeight: '',
					idCardNumber: '',
					toDate: '',
					isCollapsed: isCollapsed
				}
			},
			// 显示新增司机弹出框
			showAddDriverPopup() {
				this.$refs.addDriverPopup.open();
			},
			// 关闭新增司机弹出框
			closeAddDriverPopup() {
				this.$refs.addDriverPopup.close();
				// 关闭弹窗时重置 newDriver
				this.newDriver = this.resetDriver(true);
			},
			// 新增司机
			addNewDriver() {
				// 首先检查车牌号是否为空
				if (this.newDriver.licensePlate.length < 7) {
					this.$modal.msgError('请输入车牌号');
					return;
				}

				try {
					this.$refs.addDriverForm.validate().then(() => {
						// 如果是编辑模式，更新现有司机信息
						if (this.currentDriverIndex !== null) {
							// 使用 Vue.set 或 this.$set 来确保响应式更新
							this.$set(this.form.drivers, this.currentDriverIndex, {
								...this.newDriver,
								isCollapsed: true
							});
						} else {
							// 如果是新增模式，添加新司机
							// 使用 Vue.set 或 this.$set 来确保响应式更新
							this.form.drivers.push({
								...this.newDriver,
								isCollapsed: true
							});
						}

						// 关闭弹窗并重置表单
						this.countNumber();
						this.closeAddDriverPopup();
					}).catch(err => {
						this.$modal.msgError(err[0].errorMessage);
					});
				} catch (error) {
					console.log(error);
				}
			},
			// 添加司机
			addDriver() {
				this.currentDriverIndex = null;
				this.newDriver = this.resetDriver(true);
				this.showAddDriverPopup();
			},
			// 删除司机信息的方法
			removeDriver(index) {
				if (this.form.drivers[index].id) {
					uni.showModal({
						title: '提示',
						content: '该司机信息已存储，是否删除？点是删除',
						success: (res) => {
							if (res.confirm) {
								const datainfo = {
									id: this.form.drivers[index].id,
								};
								delPlanItem(datainfo).then(resp => {
									if (resp.code === 200) {
										this.form.drivers.splice(index, 1);
										this.countNumber();
										uni.showToast({
											title: '删除成功',
											icon: 'success'
										});
									} else {
										this.$modal.msgError("删除失败");
									}
								});

							} else if (res.cancel) {
								console.log('用户取消删除');
							}
						}
					});
				} else {
					// 若司机信息的 id 为空，直接删除该司机信息
					this.form.drivers.splice(index, 1);
				}
			},
			// 数据反馈
			dataFeedback() {
				// 回显客户信息
				if (this.goodInfoDetail.userInfo) {
					if (this.goodInfoDetail.userInfo.isContract == null) {
						this.value = 0;
					} else {
						this.value = parseInt(this.goodInfoDetail.userInfo.isContract, 10); // 转换为整数
					}
					this.billStatus = this.goodInfoDetail.userInfo.billStatus;
					this.form.customerCode = this.goodInfoDetail.userInfo.customerCode;
					this.form.accountId = parseInt(this.goodInfoDetail.userInfo.accountId, 10);
					this.form.reportDate = this.goodInfoDetail.userInfo.submissionDate;
					this.form.submitPrice = this.goodInfoDetail.userInfo.submitPrice;
					if (this.goodInfoDetail.userInfo.fileName != null) {
						const contract = {
							name: this.goodInfoDetail.userInfo.fileName,
							path: this.goodInfoDetail.userInfo.contractAddress
						};
						this.contractList.push(contract);
					}

					this.selectCustomer(this.goodInfoDetail.userInfo.customerName);
					this.selectAccountId(1);
					// 先判断已完成单子
					if (this.goodInfoDetail.userInfo.completionStatus == '1') {
						this.isAgree = true;
						this.checkboxDisabled = true;
					} else if (this.billStatus === '1' || this.billStatus === '3') {
						this.isAgree = true;
						this.checkboxDisabled = true;
					} else {
						this.checkboxDisabled = false;
					}
				}

				if (this.goodInfoDetail.driverInfo) {
					this.form.drivers = this.goodInfoDetail.driverInfo.map(driver => {
						// 为每个司机对象添加 isCollapsed 属性并设置为 true
						return {
							...driver,
							isCollapsed: true
						};
					});
				}

				// 回显所选商品信息
				if (this.goodInfoDetail.selectedGoods) {
					this.selectedGood = this.goodInfoDetail.selectedGoods;
					if ('72' == this.selectedGood.goodCategoryId) {
						this.isDate = true;
					}
				}

				this.form.handlerCode = this.goodInfoDetail.userInfo.handlerCode || null;
				// 回显公户名称和经办人选项
				this.selectCustomer(this.goodInfoDetail.userInfo.customerName);
				this.selectHandler(this.goodInfoDetail.userInfo.handlerName);
			},
			// 单价
			priceToFixed() {

				if (this.billStatus === '1' || this.billStatus === '2' || this.billStatus === '3') {
					if (this.form.submitPrice === null || this.form.submitPrice === undefined) {
						this.form.submitPrice = 0;
					}
					return this.form.submitPrice.toFixed(2);
				} else {
					if (this.selectedGood.price === null || this.selectedGood.price === undefined) {
						this.selectedGood.price = 0;
					}
					return this.selectedGood.price.toFixed(2);
				}
			},
			// 计算总价
			calculateTotalPrice() {
				if (this.billStatus === '1' || this.billStatus === '2' || this.billStatus === '3') {
					return (this.selectedGood.count * this.form.submitPrice).toFixed(2);
				} else {
					return (this.selectedGood.count * this.selectedGood.price).toFixed(2);
				}
				// return (totalWeight * this.selectedGood.price).toFixed(2);
			},
			countNumber() {
				let totalWeight = 0;
				// 遍历所有司机信息，累加装车吨位
				this.form.drivers.forEach(driver => {
					const weight = parseFloat(driver.carWeight);
					if (!isNaN(weight)) {
						totalWeight += weight;
					}
				});
				this.selectedGood.count = totalWeight;
			},

			// 选择客户
			selectCustomer(val) {
				this.customerParams.customerName = val;
				selectCardNumberInfo(this.customerParams).then(resp => {
					this.customerCodeOption = resp.data;
				});
			},
			// 选择银行户头
			selectAccountId(flag) {
				// 如果没有客户代码，直接清空账户信息并返回
				if (!this.form.customerCode) {
					this.form.accountId = null;
					this.accountIdOption = [];
					return;
				}

				this.accountParams.codeId = this.form.customerCode;
				selectAccountInfo(this.accountParams).then(resp => {
					this.accountIdOption = resp.data;
					if (flag) {
						this.form.accountId = this.goodInfoDetail.userInfo.accountId;
						return
					}
					if (this.accountIdOption.length === 0) {
						uni.showToast({
							title: '该客户没有银行户头',
							icon: 'none'
						});
						this.form.accountId = null;
						return
					}
					this.form.accountId = this.accountIdOption[0].accountId;
				});
			},
			// 关闭调度页面
			closeDispatchPage() {
				uni.navigateBack();
			},
			// 提交订单
			submitOrder(isCommit) {
				if (!this.isAgree) {
					this.$modal.msgError('请先阅读并同意下方提示');
					this.isPageLoading = false;
					return;
				}
				this.isPageLoading = true;

				getGoodInfoNew(this.selectedGood.commodityId).then(res => {
					this.newForm = res.data;
					if (this.newForm.price !== this.selectedGood.price) {
						this.selectedGood.price = this.newForm.price;
					}
				})

				this.$refs.form.validate().then(() => {
					const userInfo = {
						customerCode: this.form.customerCode,
						accountId: this.form.accountId,
						isValue: this.value,
						fileName: this.fileName,
						filePath: this.filePath,
						reportDate: this.form.reportDate,
						handlerCode: this.form.handlerCode
					};

					// 收集司机信息
					const driverInfo = this.form.drivers.filter(driver => {
						// 定义需要收集的属性
						const requiredFields = ['licensePlate', 'driverName', 'phoneNumber', 'carWeight',
							'idCardNumber', 'toDate', 'remarks'
						];
						return requiredFields.some(field => driver[field] && String(driver[field])
							.trim() !== '');
					}).map(driver => {
						// 只返回需要的属性
						const {
							licensePlate,
							driverName,
							phoneNumber,
							carWeight,
							idCardNumber,
							toDate,
							remarks
						} = driver;
						return {
							licensePlate,
							driverName,
							phoneNumber,
							carWeight,
							idCardNumber,
							toDate,
							remarks
						};
					});


					if (driverInfo.length == 0) {
						this.$modal.msgError('必须要添加至少一个司机信息');
						this.isPageLoading = false;
						return;
					}

					// 检查商品数量是否为空
					if (!this.selectedGood.count || String(this.selectedGood.count).trim() === '') {
						this.$modal.msgError('请输入商品数量');
						this.isPageLoading = false;
						return;
					}
					if (isCommit) {
						// 校验系统配置参数
						for (let w = 0; w < this.parameterList.length; w++) {
							const data = this.parameterList[w];
							if ('1' == data.isEnable && 'controlPlanTime' == data.parameterKey) {
								const [startHour, endHour] = data.parameterValue.split('-').map(Number);
								if (isNaN(startHour) || isNaN(endHour)) {
									this.$modal.msgError('系统参数配置错误：时间范围格式不正确');
									this.isPageLoading = false;
									return;
								}
								const currentHour = new Date().getHours();
								if (!(currentHour >= startHour && currentHour <= endHour)) {
									this.$modal.msgError(`订单提报时间为${startHour}:00-${endHour}:00时`);
									this.isPageLoading = false;
									return;
								}
							}
							/* if (this.isDate) {
								if ('1' == data.isEnable && 'controlDate' == data.parameterKey) {
									const today = new Date();
									today.setHours(0, 0, 0, 0);
									const tomorrow = new Date(today);
									tomorrow.setDate(tomorrow.getDate() + 1);
									const reportDate = new Date(this.form.reportDate);
									reportDate.setHours(0, 0, 0, 0);

									if (reportDate < today || reportDate > tomorrow) {
										this.$modal.msgError('提报日期必须为今天或明天');
										this.isPageLoading = false;
										return;
									}
								}
							} */
						}
					}
					//循环判断司机信息
					const licensePlates = new Set();
					for (let i = 0; i < driverInfo.length; i++) {
						const driver = driverInfo[i];
						const licensePlate = driver.licensePlate;
						const phoneNumber = driver.phoneNumber;
						const idCardNumber = driver.idCardNumber;
						if (licensePlates.has(licensePlate)) {
							this.$modal.msgError(`车牌号 ${licensePlate} 已存在，请勿重复添加`);
							this.isPageLoading = false;
							return;
						}
						licensePlates.add(licensePlate);
						const licensePlateRegex =
							/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[A-HJ-NP-Z]{1}[A-HJ-NP-Z0-9]{5,6}$/;
						if (!licensePlateRegex.test(licensePlate)) {
							this.$modal.msgError(`司机信息${i + 1}请输入有效的车牌号`);
							this.isPageLoading = false;
							return;
						}

						const phoneNumberRegex = /^1[3-9]\d{9}$/;
						if (!phoneNumberRegex.test(phoneNumber)) {
							this.$modal.msgError(`司机信息${i + 1}请输入有效的手机号码`);
							this.isPageLoading = false;
							return;
						}

						// 仅当身份证号存在时才验证格式
						if (driver.idCardNumber && driver.idCardNumber.trim() !== '') {
							const idCardRegex =
								/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
							if (!idCardRegex.test(driver.idCardNumber)) {
								this.$modal.msgError(`司机信息${i + 1}请输入有效的身份证号`);
								this.isPageLoading = false;
								return;
							}
						}
					}

					// if (issubmit) {
					getGoodInfoNew(this.selectedGood.commodityId).then(res => {
						this.newForm = res.data;

						const datainfo = {
							userInfo,
							driverInfo,
							selectedGoods: [this.selectedGood],
							isCommit: isCommit,
						};
						if (this.newForm.price !== this.selectedGood.price) {
							this.selectedGood.price = this.newForm.price;
							uni.showModal({
								title: '提示',
								content: `当前【${this.newForm.commodityName}】的单价为:【${this.newForm.price}元/吨】是否继续提报`,
								confirmText: '同意提交',
								success: (res) => {
									if (res.confirm) {
										// 表单验证通过，提交数据
										editGoodsInfo(datainfo).then(res => {
											if (res.code === 200) {
												this.$modal.msgSuccess("提报成功");
												uni.$emit('refreshPage');
												setTimeout(() => {
													this.isPageLoading = false;
													// uni.navigateBack();
													uni.switchTab({
														url: '/pages/goodsinfo/goodsinfo'
													});
												}, 1000);
											} else {
												this.$modal.msgError("提报失败");
											}
										})
									} else if (res.cancel) {
										this.isPageLoading = false;
										console.log('用户取消提报');
									}
								}
							});
						} else {
							uni.showModal({
								title: '提示',
								content: `当前【${this.newForm.commodityName}】的单价为:【${this.newForm.price}元/吨】是否继续提报`,
								confirmText: '同意提交',
								success: (res) => {
									if (res.confirm) {
										// 表单验证通过，提交数据
										addGoodsInfo(datainfo).then(res => {
											if (res.code === 200) {
												this.$modal.msgSuccess("提报成功");
												uni.$emit('refreshPage');
												setTimeout(() => {
													this.isPageLoading = false;
													// uni.navigateBack();
													uni.switchTab({
														url: '/pages/goodsinfo/goodsinfo'
													});
												}, 1000);
											} else {
												this.$modal.msgError("提报失败");
											}
										})
									} else if (res.cancel) {
										this.isPageLoading = false;
										console.log('用户取消提报');
									}
								}
							});
						}
					})
					// } else {
					// 	// 表单验证通过，提交数据
					// 	editGoodsInfo(datainfo).then(res => {
					// 		if (res.code === 200) {
					// 			this.$modal.msgSuccess(issubmit ? "提报成功" : "保存成功");
					// 			uni.$emit('refreshPage');
					// 			setTimeout(() => {
					// 				this.isPageLoading = false;
					// 				uni.navigateBack();
					// 			}, 1000);
					// 		} else {
					// 			this.$modal.msgError(issubmit ? "提报失败" : "保存失败");
					// 		}
					// 	})
					// }
				}).catch(err => {
					this.isPageLoading = false;
					// 验证失败，显示错误信息
					// this.$modal.msgError(err[0].errorMessage);
					// this.$modal.msgError(err);
					console.log(err);
				});
			},

			// 编辑订单
			editOrder(issubmit) {
				// 只有提报时才校验 isAgree
				if (issubmit && !this.isAgree) {
					this.$modal.msgError('请先阅读并同意下方提示');
					this.isPageLoading = false;
					return;
				}
				this.isPageLoading = true;

				this.$refs.form.validate().then(() => {

					const userInfo = {
						customerCode: this.form.customerCode,
						accountId: this.form.accountId,
						billNumber: this.billNumber,
						isValue: this.value,
						fileName: this.fileName,
						filePath: this.filePath,
						reportDate: this.form.reportDate,
						handlerCode: this.form.handlerCode
					};

					// 收集司机信息
					const driverInfo = this.form.drivers.filter(driver => {
						return Object.values(driver).some(value => value && String(value).trim() !== '');
					});
					if (driverInfo.length === 0) {
						this.$modal.msgError('必须添加一条司机信息');
						this.isPageLoading = false;
						return;
					}

					//循环判断司机信息
					const licensePlates = new Set();
					for (let i = 0; i < driverInfo.length; i++) {
						const driver = driverInfo[i];
						const licensePlate = driver.licensePlate;
						const phoneNumber = driver.phoneNumber;
						if (licensePlates.has(licensePlate)) {
							this.$modal.msgError(`车牌号 ${licensePlate} 已存在，请勿重复添加`);
							this.isPageLoading = false;
							return;
						}
						licensePlates.add(licensePlate);
						// 验证车牌号
						const licensePlateRegex =
							/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[A-HJ-NP-Z]{1}[A-HJ-NP-Z0-9]{5,6}$/;
						if (!licensePlate || !licensePlateRegex.test(licensePlate)) {
							this.$modal.msgError(`司机信息${i + 1}请输入有效的车牌号`);
							this.isPageLoading = false;
							return;
						}

						// 验证手机号
						const phoneNumberRegex = /^1[3-9]\d{9}$/;
						if (!phoneNumber || !phoneNumberRegex.test(phoneNumber)) {
							this.$modal.msgError(`司机信息${i + 1}请输入有效的手机号码`);
							this.isPageLoading = false;
							return;
						}

						// 仅当身份证号存在时才验证格式
						if (driver.idCardNumber && driver.idCardNumber.trim() !== '') {
							const idCardRegex =
								/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
							if (!idCardRegex.test(driver.idCardNumber)) {
								this.$modal.msgError(`司机信息${i + 1}请输入有效的身份证号`);
								this.isPageLoading = false;
								return;
							}
						}
					}
					if (issubmit) {
						// 校验系统配置参数
						for (let w = 0; w < this.parameterList.length; w++) {
							const data = this.parameterList[w];
							if ('1' == data.isEnable && 'controlPlanTime' == data.parameterKey) {
								const [startHour, endHour] = data.parameterValue.split('-').map(Number);
								if (isNaN(startHour) || isNaN(endHour)) {
									this.$modal.msgError('系统参数配置错误：时间范围格式不正确');
									this.isPageLoading = false;
									return;
								}
								const currentHour = new Date().getHours();
								if (!(currentHour >= startHour && currentHour <= endHour)) {
									this.$modal.msgError(`订单提报时间为${startHour}:00-${endHour}:00时`);
									this.isPageLoading = false;
									return;
								}
							}
							/* if (this.isDate) {
								if ('1' == data.isEnable && 'controlDate' == data.parameterKey) {
									const today = new Date();
									today.setHours(0, 0, 0, 0);
									const tomorrow = new Date(today);
									tomorrow.setDate(tomorrow.getDate() + 1);
									const reportDate = new Date(this.form.reportDate);
									reportDate.setHours(0, 0, 0, 0);
									if (reportDate < today || reportDate > tomorrow) {
										this.$modal.msgError('提报日期必须为今天或明天');
										this.isPageLoading = false;
										return;
									}
								}
							} */
						}
					}

					// 检查商品数量是否为空
					if (!this.selectedGood.count || String(this.selectedGood.count).trim() === '') {
						this.$modal.msgError('请输入商品数量');
						this.isPageLoading = false;
						return;
					}

					const datainfo = {
						userInfo,
						driverInfo,
						selectedGoods: [this.selectedGood],
						issubmit: issubmit,
					};

					if (issubmit) {
						getGoodInfoNew(this.selectedGood.commodityId).then(res => {
							this.newForm = res.data;
							if (this.newForm.price !== this.selectedGood.price) {
								this.selectedGood.price = this.newForm.price;

								uni.showModal({
									title: '提示',
									content: `当前【${this.selectedGood.commodityName}】的单价为:【${this.selectedGood.price}元/吨】是否继续提报`,
									confirmText: '同意提交',
									success: (res) => {
										if (res.confirm) {
											// 表单验证通过，提交数据
											editGoodsInfo(datainfo).then(res => {
												if (res.code === 200) {
													this.$modal.msgSuccess(issubmit ?
														"提报成功" : "保存成功");
													uni.$emit('refreshPage');
													setTimeout(() => {
														this.isPageLoading =false;
														// uni.navigateBack();
														uni.switchTab({
															url: '/pages/goodsinfo/goodsinfo'
														});
													}, 1000);
												} else {
													this.$modal.msgError(issubmit ?
														"提报失败" : "保存失败");
												}
											})
										} else if (res.cancel) {
											this.isPageLoading = false;
											console.log('用户取消提报');
										}
									}
								});
							} else {
								uni.showModal({
									title: '提示',
									content: `当前【${this.selectedGood.commodityName}】的单价为:【${this.selectedGood.price}元/吨】是否继续提报`,
									confirmText: '同意提交',
									success: (res) => {
										if (res.confirm) {
											// 表单验证通过，提交数据
											editGoodsInfo(datainfo).then(res => {
												if (res.code === 200) {
													this.$modal.msgSuccess(issubmit ?
														"提报成功" : "保存成功");
													uni.$emit('refreshPage');
													setTimeout(() => {
														this.isPageLoading =false;
														// uni.navigateBack();
														uni.switchTab({
															url: '/pages/goodsinfo/goodsinfo'
														});
													}, 1000);
												} else {
													this.$modal.msgError(issubmit ?
														"提报失败" : "保存失败");
												}
											})
										} else if (res.cancel) {
											this.isPageLoading = false;
											console.log('用户取消提报');
										}
									}
								});
							}
						})
					} else {
						// 表单验证通过，提交数据
						editGoodsInfo(datainfo).then(res => {
							if (res.code === 200) {
								this.$modal.msgSuccess(issubmit ? "提报成功" : "保存成功");
								uni.$emit('refreshPage');
								setTimeout(() => {
									this.isPageLoading = false;
									// uni.navigateBack();
									uni.switchTab({
										url: '/pages/goodsinfo/goodsinfo'
									});
								}, 1000);
							} else {
								this.$modal.msgError(issubmit ? "提报失败" : "保存失败");
							}
						})
					}
				}).catch(err => {
					// 验证失败，显示错误信息
					this.isPageLoading = false;
					this.$modal.msgError(err[0].errorMessage);
				});
			},
			// 删除商品
			removeGoods(index) {
				this.selectedGood.count = 0;
				uni.navigateBack();
			},
			// 撤销提报
			cancelReport() {
				// 调用撤销提报的接口
				cancelPlan({
					billNumber: this.billNumber
				}).then(res => {
					if (res.code === 200) {
						this.$modal.msgSuccess("撤销提报成功");
						uni.$emit('refreshPage');
						setTimeout(() => {
							uni.navigateBack();
						}, 1000);
					} else {
						this.$modal.msgError("撤销提报失败");
					}
				});
			},
			// 减少商品数量
			decreaseCount() {
				if (this.selectedGood.count > 0) {
					this.selectedGood.count--;
				}
			},
			// 增加商品数量
			increaseCount() {
				this.selectedGood.count++;
			},
			// 删除合同
			removeContract(index) {
				const datainfo = {
					billNumber: this.billNumber,
					isContract: this.value,
				};
				editContract(datainfo).then(resp => {
					if (resp.code === 200) {
						this.contractList = [];
						this.fileName = null;
						this.filePath = null;
						/* this.fileName = null;
						this.filePath = null; */
						this.$modal.msgSuccess("删除合同成功");
					} else {
						this.$modal.msgError("删除合同失败");
					}
				});
			},
			// 预览合同
			previewContract(contract) {
				// 获取文件扩展名
				const fileExtension = contract.name.split('.').pop().toLowerCase();

				// 根据文件类型选择不同的预览方式
				if (['doc', 'docx'].includes(fileExtension)) {
					// Word文档预览
					uni.downloadFile({
						url: contract.path,
						success: (res) => {
							if (res.statusCode === 200) {
								uni.openDocument({
									filePath: res.tempFilePath,
									fileType: 'docx', // 指定文件类型为docx
									success: () => {
										console.log('打开文档成功');
									},
									fail: (err) => {
										console.error('打开文档失败', err);
										uni.showToast({
											title: '打开文档失败',
											icon: 'none'
										});
									}
								});
							}
						},
						fail: (err) => {
							console.error('下载文件失败', err);
							uni.showToast({
								title: '下载文件失败',
								icon: 'none'
							});
						}
					});
				} else if (fileExtension === 'pdf') {
					// PDF文件预览
					uni.downloadFile({
						url: contract.path,
						success: (res) => {
							if (res.statusCode === 200) {
								uni.openDocument({
									filePath: res.tempFilePath,
									success: () => {
										console.log('打开文档成功');
									},
									fail: (err) => {
										console.error('打开文档失败', err);
										uni.showToast({
											title: '打开文档失败',
											icon: 'none'
										});
									}
								});
							}
						},
						fail: (err) => {
							console.error('下载文件失败', err);
							uni.showToast({
								title: '下载文件失败',
								icon: 'none'
							});
						}
					});
				} else {
					uni.showToast({
						title: '不支持的文件类型',
						icon: 'none'
					});
				}
			},
			onHandlerChange(e) {
				const selected = this.customerCodeOption.find(item => item.commonCode === e);
				this.form.handlerName = selected ? selected.showValue : '';
			},
			selectHandler(val) {
				this.handlerParams.customerName = val;
				selectCardNumberInfo(this.handlerParams).then(resp => {
					this.handlerCodeOption = resp.data;
				});
			},
			checkboxChange(e) {
				if (this.checkboxDisabled) return;
				this.isAgree = e.detail.value.length > 0;
			},
		},
		computed: {
			showResubmitButton() {
				// billStatus 可能为数字或字符串，统一转字符串判断
				const billStatus = String(this.billStatus);
				// completionStatus 来源于 goodInfoDetail.userInfo.completionStatus 或 isSuccess
				let completionStatus = null;
				if (this.goodInfoDetail && this.goodInfoDetail.userInfo && this.goodInfoDetail.userInfo.completionStatus !== undefined) {
					completionStatus = String(this.goodInfoDetail.userInfo.completionStatus);
				} else if (this.isSuccess !== undefined) {
					completionStatus = String(this.isSuccess);
				} else {
					completionStatus = '0';
				}
				return (
					(billStatus === '3' && completionStatus === '1') ||
					(billStatus === '1' && completionStatus === '0') ||
					(billStatus === '3')
				);
			}
		}
	};
</script>


<style lang="scss" scoped>
	// 变量定义
	$primary-color: #3498db;
	$success-color: #4CAF50;
	$danger-color: #f44336;
	$text-primary: #2c3e50;
	$text-secondary: #495057;
	$border-color: #e9ecef;
	$bg-light: #f8f9fa;
	$white: #fff;

	// 混合器
	@mixin flex-center {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	@mixin card-base {
		border: 1px solid $border-color;
		padding: 0 10px;
		margin-bottom: 16px;
		border-radius: 8px;
		position: relative;
		background-color: $white;
		box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
		transition: box-shadow 0.2s ease;

		&:hover {
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
		}
	}

	.edit-column {
		flex-direction: column;
		gap: 20rpx !important;
	}

	// 容器样式
	.container {
		padding: 16px;
		padding-bottom: 170rpx;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
		display: flex;
		flex-direction: column;
		background-color: $bg-light;
	}

	// 标题样式
	.section-title {
		display: flex;
		align-items: center;
		font-size: 15px;
		font-weight: 500;
		color: $text-primary;
		padding: 12px;
		border-bottom: 1px #EBEEF5 solid;
	}

	.form-container {
		padding: 10px;
	}

	// 通用卡片样式
	.customer-info,
	.driver-info,
	.contract-info {
		@include card-base;
	}

	.driver-content {
		padding: 15px;
	}

	.driver-content-text {
		font-size: 14px;
		color: #666;
		line-height: 20px;
	}

	// 合同列表的样式
	.contract-list {
		ul {
			list-style: none;
			padding: 0;
			margin: 0;

			li {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 10px;

				.contract-actions {
					display: flex;
					align-items: center;
				}
			}
		}
	}

	// 按钮容器样式
	.button-container {
		margin-top: 16px;
		padding: 8px 16px 8px 16px; /* 上下左右padding调小 */
		background-color: $white;
		border-radius: 8px;
		box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		margin: 0;
		/* z-index: 100; */

		.button-group {
			display: flex;
			justify-content: flex-end;
			gap: 12px;
		}
	}

	// 弹出框样式
	.popup-content {
		display: flex;
		flex-direction: column;
		gap: 20px;
		width: 100%;
		// max-width: 600rpx;  /* 限制最大宽度 */
		padding: 30rpx;
		background-color: $white;
		border-radius: 12rpx;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
	}

	/* 表单样式优化 */
	:deep(.uni-forms-item) {
		margin-bottom: 16rpx;

		.uni-forms-item__label {
			font-size: 28rpx;
			color: #333;
		}

		.uni-easyinput__content,
		.uni-date {
			border: 1px solid #DCDFE6;
			border-radius: 4rpx;

			&:hover {
				border-color: #409EFF;
			}
		}
	}

	/* 按钮组样式 */
	.button-group {
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1px solid #EBEEF5;
	}

	/* 车牌号输入组件样式 */
	// :deep(.license-plate-container) {
	// 	margin-bottom: 20rpx;
	// 	padding: 0;

	// 	.title {
	// 		margin-bottom: 20rpx;
	// 		font-size: 28rpx;
	// 		color: #333;
	// 	}
	// }

	.goods-info {
		background: #fff;
		border-radius: 8px;
		margin: 10px 0;
		padding: 0;

	}

	.goods-card {
		padding: 10px;
	}

	.goods-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 10px;
		border-bottom: 1px #EBEEF5 solid;
	}

	.select-icon {
		display: flex;
		align-items: center;
		gap: 4px;

		text {
			font-size: 14px;
			color: #666;
		}
	}

	.goods-content {
		display: flex;
		align-items: center;
		gap: 12px;
		padding-top: 10px 0;
	}

	.goods-image {
		width: 80px;
		height: 80px;
		border-radius: 4px;
	}

	.goods-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.goods-name {
		font-size: 14px;
		color: #333;
		font-weight: 500;
	}

	.goods-unit {
		font-size: 12px;
		color: #666;
	}

	.goods-price {
		font-size: 14px;
		color: #f56c6c;
		font-weight: 500;
	}

	.goods-quantity {
		display: flex;
		align-items: center;
		gap: 1px;
		margin-top: 50px;
	}

	.quantity-btn {
		width: 28px;
		height: 28px;
		border: 1px solid #dcdfe6;
		background: #fff;
		color: #606266;
		font-size: 16px;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0;
	}

	.quantity-input {
		width: 55px;
		height: 28px;
		border: 1px solid #dcdfe6;
		text-align: center;
		font-size: 14px;
		color: #606266;
		z-index: 0;
	}

	.quantity-input-number {
		width: 75px;
		height: 28px;
		border: 1px solid #dcdfe6;
		text-align: center;
		font-size: 14px;
		color: #606266;
		z-index: 0;
	}

	::v-deep .uni-collapse-item__title-box {
		padding: 0 10px !important;
	}

	.zxz-uni-data-select .uni-data-select__input {
	  white-space: nowrap; /* 禁止文本换行 */
	  overflow: hidden;    /* 隐藏超出内容 */
	  text-overflow: ellipsis; /* 超出部分显示省略号 */
	}

	.xieyi {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		gap: 4px;
		min-height: 24px;
	}

	.xieyi .text-grey1 {
		font-size: 12px !important;
		line-height: 18px;
		margin-left: 2px;
	}
	// 待定 20250627 输入框超出问题 限定px可能导致不同型号输入框不一致问题
	::v-deep .uni-select {
	  max-width: 230px;
	}
</style>
